package com.hitqz.robot.camera.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Table;
import com.hitqz.robot.api.business.enums.VoiceEnum;
import com.hitqz.robot.api.business.event.EquipmentPoseUpdateEvent;
import com.hitqz.robot.api.business.event.PlayVoiceEvent;
import com.hitqz.robot.api.common.dto.robot.RobotOnlineEventDto;
import com.hitqz.robot.api.common.entity.RobotEquipmentPose;
import com.hitqz.robot.camera.HikVisionService;
import com.hitqz.robot.camera.communication.NetworkServiceThreadPool;
import com.hitqz.robot.camera.configure.EquipmentCmdEnum;
import com.hitqz.robot.camera.dto.EquipmentParamsDto;
import com.hitqz.robot.camera.dto.QueryParamsDto;
import com.hitqz.robot.camera.dto.VoicePlayDto;
import com.hitqz.robot.camera.entity.ConstantsFace;
import com.hitqz.robot.camera.entity.HkCameraDriver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.Objects;


@Component
@Slf4j
public class CameraEventListener {

    @Autowired
    private HikVisionService hkCamera;
    @Autowired
    private RestTemplate restTemplate;

    @Value("${cvd.nav-wav-path:}")
    private String navWavPath;

    private static int lastOnlineStatus = 0;

    private final static String AUDIO_PLAY_URL = "http://127.0.0.1:8181/audio/play";

    //测温初始化设置
    @Async("cameraInitExecutor")
    @EventListener
    public void onHkInitHotEvent(HkCameraDriver cameraDriver) {
        synchronized (cameraDriver.getIp().intern()) {
            //获取测温能力集
            if (hkCamera.getThermalCap(cameraDriver)) {
                //获取测温模式能力集
                hkCamera.getThermometryMode(cameraDriver);
                //设置测温模式
                hkCamera.initThermometryMode(cameraDriver);
                //设置区域
                hkCamera.setRegion(cameraDriver, null, true);
                //ptz能力集
                hkCamera.getPTZCap(cameraDriver);
                hkCamera.getPTZAbsoluteExCap(cameraDriver);
                hkCamera.getImageCap(cameraDriver);
            }
        }
    }


    @Async("cameraInitExecutor")
    @EventListener
    public void onUpdatePoseEvent(EquipmentPoseUpdateEvent event) {
        if (!Objects.equals(event.getBrand().toUpperCase(), hkCamera.brand().getEnStr().toUpperCase())) {
            return;
        }
        //删除旧值
        String ip = event.getIp();
        Table<String, String, String> paramsCacheTable = hkCamera.getParamsCacheTable();
        paramsCacheTable.rowMap().remove(ip);
        //缓存新的值
        for (RobotEquipmentPose pose : event.getPoseList()) {
            paramsCacheTable.put(ip, pose.getTypeStr(), pose.getJson());
        }

    }

    @Async("cameraInitExecutor")
    @EventListener
    public void onRobotOnlineEvent(RobotOnlineEventDto event) {
        NetworkServiceThreadPool.dealEvent(() -> {
            Integer onlineStatus = event.getOnlineStatus();
            if (onlineStatus == null) {
                return;
            }
            if (!Objects.equals(lastOnlineStatus, onlineStatus) && Objects.equals(onlineStatus, 1)) {
                for (HkCameraDriver driver : ConstantsFace.HK_CAMERA_DRIVER_MAP.values()) {
                    QueryParamsDto query = new QueryParamsDto();
                    query.setIp(driver.getIp());
                    List<EquipmentParamsDto> deviceParamsData = hkCamera.getDeviceParamsData(query, EquipmentCmdEnum.GET_ORIGIN_PARAMS);
                    hkCamera.setEquipmentParams(query, deviceParamsData, true);
                }
                log.info("[HK]上线回到初始姿态");
            }
            lastOnlineStatus = onlineStatus;
        });
    }


    @EventListener
    public void onPlayVideoEvent(PlayVoiceEvent event) {
        if (!ConstantsFace.voicePlayEnable) {
            return;
        }
        if (!StringUtils.hasText(navWavPath)) {
            return;
        }
        NetworkServiceThreadPool.dealEvent(() -> {
            VoiceEnum voiceEnum = event.getVoiceEnum();
            String fileName = voiceEnum.getName();
            this.voiceOperate(0, navWavPath + fileName + ".wav");
        });
    }

    /**
     * 语音操作接口
     *
     * @param operate 操作：0-开始播放、1-停止播放、2-暂停播放、3-恢复播放
     * @param wavPath 音频文件路径
     */
    private void voiceOperate(int operate, String wavPath) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
        String body = JSONUtil.toJsonStr(Map.of("operate", operate, "wavPath", wavPath));
        HttpEntity<String> strEntity = new HttpEntity<String>(body, headers);
//        log.info("机器人导航状态语音播报操作接口，入参：{}", body);
        String result = restTemplate.postForObject(AUDIO_PLAY_URL, strEntity, String.class);
//        log.info("机器人导航状态语音播报操作接口，结果：{}", result);
    }


}
